import EventEmitter from './utils/event' // 事件总线
import { codeLogin } from './api/user'
import { login } from './utils/permission'

App({
  /**
   * 全局事件总线
   */
  event: new EventEmitter(),

  onLaunch() {
    // 自动登录
    // autoLogin()
    this.autoCodeLogin()
  },
  globalData: {
    userInfo: {
      name: '',
      department: ''
    }
  },

  autoCodeLogin() {
    wx.showLoading({
      title: '登录中...',
      mask: true
    })  
    wx.login()
      .then((res) => {
        return codeLogin({
          code: res.code
        })
      })
      .then((res) => {
        let user = {
          name: res.data.name,
          department: res.data.department
        }
        login(res.data.token, user)
        this.event.emit('loginStatusChanged')
        if (!user.name || !user.department) {
          wx.navigateTo({
            url: '/pages/userInfo/fill/fill',
            success: function () {
              wx.showToast({
                title: '请完善个人信息'
              })
            }
          })
        }
      })
      .finally(() => {
        wx.hideLoading()
      })
  },

  /**
   * 设置用户信息
   * @event <userInfoChanged> 在我的(mine)被监听
   */
  setUserInfo: function (userInfo) {
    this.globalData.userInfo = Object.assign(
      {},
      this.globalData.userInfo,
      userInfo
    )
    this.event.emit('userInfoChanged', { userInfo: userInfo })
  }
})
